﻿/////////////////////////////////////////////////////////////////////////////////////////////
// <copyright file="OnPremiseSessionRunspace.cs" company="Microsoft Corporation">
//     Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
/////////////////////////////////////////////////////////////////////////////////////////////

namespace Microsoft.LiveAtEdu.Samples.Powershell.OnPremise
{
    using System;
    using System.Management.Automation.Runspaces;
    using System.Security;

    /// <summary>
    /// SessionRunspace implementation for OnPremise scenario.
    /// </summary>
    internal class OnPremiseSessionRunspace : SessionRunspace
    {
        /// <summary>
        /// Initializes a new instance of the OnPremiseSessionRunspace class.
        /// </summary>
        /// <param name="userName">The user name to authenticate the session.</param>
        /// <param name="password">The password to authenticate the session.</param>
        /// <param name="connectionUri">Uri for creating the connection.</param>
        public OnPremiseSessionRunspace(string userName, SecureString password, string connectionUri)
        {
            if (string.IsNullOrEmpty(userName))
            {
                throw new ArgumentOutOfRangeException("userName");
            }

            if (password == null)
            {
                throw new ArgumentOutOfRangeException("password");
            }

            if (string.IsNullOrEmpty(connectionUri))
            {
                throw new ArgumentOutOfRangeException("connectionUri");
            }

            this.SessionType = SessionType.OnPremiseSession;

            // Create the runspace.
            this.Runspace = RunspaceFactory.CreateRunspace();
            this.Runspace.Open();

            // Create the session and import it.
            var onPremiseSession = new OnPremiseSession(this.Runspace);
            this.PSSession = onPremiseSession.CreateSession(userName, password, connectionUri);
            onPremiseSession.ImportSession(this.PSSession);
        }

        /// <summary>
        /// Close the session instance.
        /// </summary>
        public override void CloseInstance()
        {
            try
            {
                var onPremiseSession = new OnPremiseSession(this.Runspace);
                onPremiseSession.ExitSession(this.PSSession);

                this.Runspace.Close();
                this.Runspace = null;
            }
            catch
            {
                // Ignore the exception
            }
        }
    }
}
